﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Medora.DataContract;
using Medora.Model.Basic;
using Medora.Model.Persons;

namespace Medora.Data
{
    public class PersonRepository : EFRepository<Person>, IPersonRepository
    {
        public PersonRepository(DbContext dbContext) : base(dbContext) { }

        public virtual Person GetById(Guid id)
        {
            var persons = DbSet.Include(x => x.Address);
            return persons.FirstOrDefault(o => o.Id == id);
        }

        public IEnumerable<Person> Get(Expression<Func<Person, bool>> filter = null, Func<IQueryable<Person>, IOrderedQueryable<Person>> orderBy = null, string includeProperties = "")
        {
            IQueryable<Person> query = DbSet.Include(x => x.Address);//.Include(o=>o.Address.Country).Include(o=>o.Address.Place);

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = QueryableExtensions.Include(query, includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query);
            }
            else
            {
                return query;
            }
        }

        public IEnumerable<Person> GetTake(int pageSize, int page, Expression<Func<Person, bool>> filter = null, SortInfo sortInfo = null, string includeProperties = "")
        {
            IQueryable<Person> query = DbSet.Include(x => x.Address);

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = QueryableExtensions.Include(query, includeProperty);
            }


           return query.Take(pageSize);
        }
    }
}